package com.weixin.project.Service;

import com.weixin.project.Common.Enum.MsgStatus;
import com.weixin.project.Common.Exception.EntityNotExistException;
import com.weixin.project.Dao.MsgDao;
import com.weixin.project.Entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
public class MsgService {
    @Value("10")
    Integer pageSize;
    @Autowired
    MsgDao msgDao;
    public Page<Message> findMessagesOfUser(Integer userId, Integer page){
        Sort sort = Sort.by("id").descending();
        Pageable pageable = PageRequest.of(page, pageSize, sort);
        return msgDao.getMessagesByReceiverId(userId, pageable);
    }

    public Integer countMessagesOfUser(Integer userId){
        return msgDao.countMessagesByReceiverId(userId);
    }

    public Integer countNotReadMessagesOfUser(Integer userId) {
        return msgDao.countMessagesByReceiverIdAndStatus(userId, MsgStatus.TO_BE_READ);
    }

    public void readMessage(Integer msgId){
        Optional<Message> msgOp = msgDao.findById(msgId);
        if (!msgOp.isPresent()) throw new EntityNotExistException("message", msgId);
        Message message = msgOp.get();
        message.setStatus(MsgStatus.HAVE_BEEN_READ);
        msgDao.save(message);
    }

    public void sendDeleteMessage(Integer userId,String className, String title){
        Message msg = new Message();
        msg.setReceiverId(userId);
        msg.setStatus(MsgStatus.TO_BE_READ);
        msg.setCreateTime(new Date());
        StringBuilder sb = new StringBuilder();
        sb.append("Your ").append(className).append(":").append("\"" + title + "\"").
                append(" has been deleted because of informed by other users");
        msg.setContent(sb.toString());
        msgDao.save(msg);
    }
}

